package internal

import (
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// 读取 /etc/hosts 文件内容
func readHostsFile() ([]string, error) {
	content, err := os.ReadFile("/etc/hosts")
	if err != nil {
		return nil, err
	}
	lines := strings.Split(string(content), "\n")
	var hosts []string
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line != "" {
			hosts = append(hosts, line)
		}
	}
	return hosts, nil
}

// 写入 /etc/hosts 文件
func writeHostsFile(hosts []string) error {
	content := strings.Join(hosts, "\n")
	return os.WriteFile("/etc/hosts", []byte(content), 0644)
}

// 获取所有 hosts 记录
func GetHosts(c *gin.Context) {
	hosts, err := readHostsFile()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, hosts)
}

// 添加一条 hosts 记录
func AddHost(c *gin.Context) {
	var data struct {
		Host string `json:"host"`
	}
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Missing 'host' field"})
		return
	}
	hosts, err := readHostsFile()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	hosts = append(hosts, data.Host)
	err = writeHostsFile(hosts)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to add host"})
		return
	}
	c.JSON(http.StatusCreated, gin.H{"message": "Host added successfully"})
}

// 修改一条 hosts 记录
func UpdateHost(c *gin.Context) {
	var data struct {
		Host string `json:"host"`
	}
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Missing 'host' field"})
		return
	}
	indexStr := c.Param("index")
	index, err := strconv.Atoi(indexStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid index"})
		return
	}
	hosts, err := readHostsFile()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if index < 0 || index >= len(hosts) {
		c.JSON(http.StatusNotFound, gin.H{"error": "Index out of range"})
		return
	}
	hosts[index] = data.Host
	err = writeHostsFile(hosts)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update host"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Host updated successfully"})
}

// 删除一条 hosts 记录
func DeleteHost(c *gin.Context) {
	indexStr := c.Param("index")
	index, err := strconv.Atoi(indexStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid index"})
		return
	}
	hosts, err := readHostsFile()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if index < 0 || index >= len(hosts) {
		c.JSON(http.StatusNotFound, gin.H{"error": "Index out of range"})
		return
	}
	hosts = append(hosts[:index], hosts[index+1:]...)
	err = writeHostsFile(hosts)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete host"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Host deleted successfully"})
}
